package com.yld.car.market;

import java.util.ArrayList;
import java.util.HashMap;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.yld.car.common.ConstantUtils;
import com.yld.car.common.NetworkProgressUtils;
import com.yld.car.domain.Car;
import com.yld.car.domain.SearchDetailCar;
import com.yld.car.domain.UserInfo;

public class CostHomePageActivity extends BaseActivity implements
		OnItemClickListener {

	private Button rightButton;
	private Button modelButton;

	private ListView carTypeList;

	private String id;
	private boolean flag = false;
	private TextView titleText;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		// 自定义标题栏
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.pay_to_car_list);
		// 设置布局
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);
		Intent i = getIntent();
		mBar = (ProgressBar) findViewById(R.id.progressBar);
		titleText = ((TextView) findViewById(R.id.title));
		utils = NetworkProgressUtils.getInstance();
		super.onCreate(savedInstanceState);

		carTypeList = (ListView) findViewById(R.id.list1);
		super.showBackButton();
		Intent intent = this.getIntent();

		if (intent != null) {
			flag = intent.getBooleanExtra("isAttention", false);
		}

		carTypeList.setOnItemClickListener(this);

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		String methodIndex = "";
		String methodURL = "";
		if (flag) {
			titleText.setText("已关注车辆");
			methodIndex = "46";
			methodURL = ConstantUtils.GET_ATTENTION_CARS_BY_DEALER_ID_URL;
		} else {
			titleText.setText("已购车辆");
			methodIndex = "45";
			methodURL = ConstantUtils.GET_ALREADY_CARS_BY_DEALER_ID_URL;
		}

		// showButton();

		new CostListTask().execute(new String[] { methodIndex, methodURL });
	}

	private ProgressBar mBar;

	private NetworkProgressUtils utils;

	private class CostListTask extends
			AsyncTask<String, String, ArrayList<Car>> {

		@Override
		protected ArrayList<Car> doInBackground(String... params) {

			HashMap<String, String> allParams = new HashMap<String, String>();
			UserInfo u = (UserInfo) readObject("userInfo");

			allParams.put("dealerId", u.getUserId());

			Object o = utils
					.getWebservicesByData(
							ConstantUtils.NAME_SPACE,
							ConstantUtils.ALL_METHROD_NAME.get(Integer
									.parseInt(params[0])),
							ConstantUtils.NAME_SPACE
									+ ConstantUtils.ALL_METHROD_NAME
											.get(Integer.parseInt(params[0])),
							params[1], allParams);

			ArrayList<Car> all = utils.parseJson(o.toString(), "table",
					NetworkProgressUtils.SEARCH_CAR_TYPE, false);

			return all;
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			mBar.setVisibility(View.VISIBLE);
		}

		@Override
		protected void onPostExecute(ArrayList<Car> result) {

			super.onPostExecute(result);

			mBar.setVisibility(View.GONE);
			if (result != null) {

				CostHomeAdapter adapter = new CostHomeAdapter(result,
						CostHomePageActivity.this);
				carTypeList.setAdapter(adapter);
			}
		}

	}

	@Override
	public void onItemClick(AdapterView<?> adapterView, View v, int position,
			long id) {

		Object o = adapterView.getAdapter().getItem(position);

		if (o instanceof SearchDetailCar) {

			final SearchDetailCar s = (SearchDetailCar) o;
			// new Thread(new Runnable() {
			//
			// /**
			// * { "recordcount":"1", --返回的数据条数 "table": [ { "no":"1", --序列号
			// * "id": "1683", --车辆ID "name": "外白内黑棕", --车辆外饰内饰简称，即这辆车的标题
			// * "classid": "111", --系列ID "press": "115", --价格（单位W） "qhtime":
			// * "2014-04-30", --到港时间（期货才有时间，现货没有时间即为空） "vin": "", --就是车架号
			// * "xppz": "运动包¤扩展真皮内饰¤红卡钳", --选配配置 "companyname": "",
			// * --这辆车所属经销商公司名称 "adddate": "2014-04-11 18:19:33", --这辆车的录入时间
			// * "pinpainame": "玛莎拉蒂", --此车品牌名称 "xiliename": "GHIBLI S Q4",
			// * --此车系列名称 "gangkouname": "张家港", --这辆车所属经销商公司所在港口 "xhorqh":
			// * "期货" --期货还是现货 } …… ] }
			// */
			// @Override
			// public void run() {
			// SQLiteDatabase sqLiteDatabase = mApp.getmDbHelper()
			// .getWritableDatabase();
			// ContentValues values = new ContentValues();
			// values.put(RecentlyViewedDBHelper.ID, s.getId());
			// values.put(RecentlyViewedDBHelper.NO, s.getNo());
			// values.put(RecentlyViewedDBHelper.NAME, s.getName());
			// values.put(RecentlyViewedDBHelper.CLASS_ID, s.getClassid());
			// values.put(RecentlyViewedDBHelper.PRESS, s.getPress());
			// values.put(RecentlyViewedDBHelper.QHTIME, s.getQhtime());
			// values.put(RecentlyViewedDBHelper.ADD_DATE, s.getAdddate());
			// values.put(RecentlyViewedDBHelper.XPPZ, s.getXppz());
			// values.put(RecentlyViewedDBHelper.COMPANY_NAME,
			// s.getCompanyname());
			// values.put(RecentlyViewedDBHelper.PIN_PAI_NAME,
			// s.getPinpainame());
			// values.put(RecentlyViewedDBHelper.XI_LIE_NAME,
			// s.getXiliename());
			// values.put(RecentlyViewedDBHelper.GANG_KOU_NAME,
			// s.getGangkouname());
			// values.put(RecentlyViewedDBHelper.XHORQH, s.getXhorgh());
			// long rowId = sqLiteDatabase.insert(
			// RecentlyViewedDBHelper.RECENT_VIEW_TABLE, null,
			// values);
			// if (rowId > 0) {
			// System.out.println("insert------>插入成功。");
			// } else {
			//
			// System.out.println("insert------>插入失败。");
			// }
			//
			// }
			// }).start();

			String cId = s.getId();
			Intent intent = new Intent();
			intent.putExtra("cId", cId);
			intent.putExtra("carName", s.getPinpainame());
			intent.putExtra("carType", s.getXhorgh());// 类型
			intent.putExtra("carSeries", s.getXiliename());

			intent.setClass(this, CarDetailInfoActivity.class);
			startActivity(intent);
		}

	}

	// @Override
	// protected void onActivityResult(int requestCode, int resultCode, Intent
	// data) {
	// // TODO Auto-generated method stub
	// super.onActivityResult(requestCode, resultCode, data);
	//
	// if (1 == requestCode && RESULT_OK == resultCode) {
	//
	// FilterCarInfo f = (FilterCarInfo) data
	// .getSerializableExtra("filter");
	//
	// // System.out.println(s);
	// // new CarTypeTask().execute(new String[] { f.color, f.type, f.port
	// // });
	// }
	// }

	public class CostHomeAdapter extends BaseAdapter {

		private ArrayList<Car> all;

		public CostHomeAdapter(ArrayList<Car> all, Context context) {
			this.all = all;
			this.context = context;
		}

		private Context context;

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return all.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return all.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			if (convertView == null) {

				convertView = LayoutInflater.from(context).inflate(
						R.layout.cost_car_items, null);
			}

			Car c = all.get(position);

			if (c instanceof SearchDetailCar) {

				final SearchDetailCar s = (SearchDetailCar) c;

				ImageView image = (ImageView) convertView
						.findViewById(R.id.itemCarImage);
				String type = s.getXhorgh();
				// System.out.println(type);
				if ("现货".equals(type)) {
					image.setImageResource(R.drawable.xianhuo);
				} else {
					image.setImageResource(R.drawable.qihuo);
				}
				TextView typeText = (TextView) convertView
						.findViewById(R.id.itemType);
				typeText.setVisibility(View.VISIBLE);
				typeText.setText(s.getPinpainame() + "-" + s.getXiliename());
				// TextView titleText = (TextView) convertView
				// .findViewById(R.id.itemTitle);
				//
				// titleText.setText(s.getPinpainame());
				TextView abbreviationText = (TextView) convertView
						.findViewById(R.id.itemAbbreviation);

				abbreviationText.setText(s.getName());
				TextView priceText = (TextView) convertView
						.findViewById(R.id.itemPrice);

				priceText.setText(s.getPress() + "万");
				TextView configText = (TextView) convertView
						.findViewById(R.id.itemSelectConfig);

				configText.setText(s.getXppz());
				TextView publishText = (TextView) convertView
						.findViewById(R.id.itemPublishDate);

				String date = s.getAdddate();
				date = date.substring(0, date.lastIndexOf(" "));
				publishText.setText(date);
				TextView dealerText = (TextView) convertView
						.findViewById(R.id.itemDealerName);
				dealerText.setText(s.getCompanyname());
				if (flag) {
					Button btn = (Button) convertView
							.findViewById(R.id.cancelAttentionBtn);
					btn.setVisibility(View.VISIBLE);
					btn.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							final String fromDealersId = ((UserInfo) readObject("userInfo"))
									.getUserId();
							new Thread(new Runnable() {

								@Override
								public void run() {

									progressAttentionCarBtn(
											fromDealersId,
											s.getId(),
											40,
											ConstantUtils.CANCEL_ATTENTION_TO_CAR_URL);

								}
							}).start();

						}
					});
				}

			}
			convertView
					.setBackgroundResource(android.R.drawable.list_selector_background);
			return convertView;
		}

	}

	private void progressAttentionCarBtn(String fromDealersId, String carId,
			int methodIndex, String methodURL) {
		HashMap<String, String> allParams = new HashMap<String, String>();

		allParams.put("fromDealersId", fromDealersId);
		allParams.put("carId", carId);

		Object o = utils.getWebservicesByData(
				ConstantUtils.NAME_SPACE,
				ConstantUtils.ALL_METHROD_NAME.get(methodIndex),
				ConstantUtils.NAME_SPACE
						+ ConstantUtils.ALL_METHROD_NAME.get(methodIndex),
				methodURL, allParams);

		Message msg = mHandler.obtainMessage();
		msg.obj = o;
		//msg.what = methodIndex;
		mHandler.sendMessage(msg);
	}

	private Handler mHandler = new Handler() {

		public void handleMessage(Message msg) {

			//System.out.println(msg.obj);
			
			
			if(msg.obj!=null&&msg.obj.toString().indexOf("操作成功")>=0){
				String methodIndex = "46";
				String methodURL = ConstantUtils.GET_ATTENTION_CARS_BY_DEALER_ID_URL;
				new CostListTask().execute(new String[] { methodIndex, methodURL });
			}
			
			
		}
	};
}
